package com.pengxh.cmake.base

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import java.io.IOException


abstract class SerialPortBaseActivity<VB : ViewBinding> : AppCompatActivity(), Handler.Callback {

    private val kTag = "SerialPortBaseActivity"
    private val weakReferenceHandler by lazy { WeakReferenceHandler(this) }
    private val serialPorts by lazy { BaseApplication.get().getSerialPorts() }
    protected lateinit var binding: VB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = initViewBinding()
        setContentView(binding.root)
        setupTopBarLayout()
        initOnCreate(savedInstanceState)
        initEvent()

        if (serialPorts.isNotEmpty()) {
            Thread {
                val buffer = ByteArray(128)
                try {
                    while (!Thread.interrupted()) {
                        val bytesRead = serialPorts.first().inputStream.read(buffer)
                        if (bytesRead > 0) {
                            weakReferenceHandler.let {
                                val message = it.obtainMessage()
                                message.what = 2025012001
                                message.obj = buffer.copyOf(bytesRead)
                                it.sendMessage(message)
                            }
                        }
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }.start()
        }
    }

    /**
     * 初始化ViewBinding
     */
    abstract fun initViewBinding(): VB

    /**
     * 特定页面定制沉浸式状态栏
     */
    abstract fun setupTopBarLayout()

    /**
     * 初始化默认数据
     */
    abstract fun initOnCreate(savedInstanceState: Bundle?)

    /**
     * 初始化业务逻辑
     */
    abstract fun initEvent()

    /**
     * 串口读数
     * */
    abstract fun onDataReceived(buffer: ByteArray)

    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == 2025012001) {
            val buffer = msg.obj as ByteArray
            Log.d(kTag, buffer.contentToString())
            onDataReceived(buffer)
        }
        return true
    }

    fun sendSerialPortCommand(command: Int) {
        if (serialPorts.isNotEmpty()) {
            val outStream = serialPorts.first().outputStream
            outStream.write(command)
            outStream.flush()
            Log.d(kTag, "sendSerialPortCommand: $command")
        }
    }

    /**
     * 停止串口数据传输
     * */
    fun stopSerialPortCommand() {
        if (serialPorts.isNotEmpty()) {
//            val outStream = serialPorts.first().outputStream
//            outStream.write(SerialPortCommand.STOP_SERIAL_PORT_DATA)
//            outStream.flush()
            Log.d(kTag, "stopSerialPortCommand: SerialPortBaseActivity")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopSerialPortCommand()
    }
}